<?php
/**
 * Copyright (c) 2021-2222   All rights reserved.
 *
 * 创建时间：2021-12-11 00:26
 *
 * 项目：levs  -  $  - cookieHelper.php
 *
 * 作者：liwei
 */

//!defined('INLEV') && exit('Access Denied LEV');


namespace modules\qq\helpers;

class cookieHelper
{

    /**
     * 将cookie转换成数组
     * $key cookie名称
     * 传入$key时返回对应值
     * 默认以数组形式返回所有cookie
     *
     * @param $qq
     * @param $key
     * @param $cookies
     * @return array|mixed
     */
    public static function cookieArrv($qq, $key, $cookies = '') {
        //$uid = Lev::$app['uid'];
        if ($cookies && !is_file($cookies)) {
            $qqlogin = 2;//2为数据存储cookie
        }else {
            $qqlogin = 1;
        }
        $cookieArr = [];
        if ($qqlogin ==2) {
            $cka = explode(';', $cookies);
            foreach ((array)$cka as $v) {
                $_cka = explode('=', $v);
                $cookieArr[trim($_cka[0])] = trim($_cka[1]);
            }
            if ($key) return $cookieArr[$key];
        }else {
            $cookieArr = static::ckfArrv($qq, $key);
        }

        return $cookieArr;
    }

    /**
     * @param $qq
     * @param $key
     * @param string $cookiefile
     * @return mixed
     */
    public static function ckfArrv($qq, $key, $cookiefile = '') {
        static $results;
        if (!isset($results[$qq])) {
            if (!$cookiefile) {
                $cookiefile = qqLoginHelper::createCK($qq);
            }
            $rs = [];
            if (is_file($cookiefile)) {
                $ckf = file($cookiefile);
                unset($ckf[0], $ckf[1], $ckf[2], $ckf[3]);
                foreach ($ckf as $k => $v) {
                    $ckfs[$k] = explode('	', $v);
                    $rs[trim($ckfs[$k][5])] = trim($ckfs[$k][6]);
                }
            }
            $results[$qq] = $rs;
        }
        if ($key) {
            return $results[$qq][$key];
        }
        return $results[$qq];
    }

    /**
     * 提取头部信息cookie值并存入数据库
     * 返回格式为字符串：confirmuin=0;ptisp=ctc;
     *
     * @param $header
     * @param null $qq
     * @return bool|string
     */
    public static function saveCookie($header, $qq = null) {
        if (!$header) return FALSE;
        //$uid = Lev::$app['uid'];
        !$qq && $qq = '';
        $cookies = '';

        $_header  = explode("\n", $header);
        foreach ($_header as $v) {
            if (strpos($v, 'Set-Cookie:') !==FALSE && strpos($v, 'HttpOnly') ===FALSE) {
                $cookies .= substr(trim($v), 11);
            }
        }
        return $cookies;
    }

}